//
//  GMMyClassVC.m
//  Teecloud
//
//  Created by 小熊 on 2018/10/22.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "GMMyClassVC.h"
#import "GMBaseNavigationController.h"
#import "GMMyClassCell.h"
#import "GMMyclassModel.h"
#import "GMReadPDFVC.h"
#import "GMBuyVideoVC.h"
#import "GMPlayerViewController.h"
#import "GMReadPDFVC.h"
#import "GMCoursePackageVC.h"
#import "GMExercisesVC.h"
#import "GMExaminationVC.h"
@interface GMMyClassVC ()<UITableViewDataSource,UITableViewDelegate,PYSearchViewControllerDelegate>
@property (nonatomic, assign) NSInteger pageIndex;
@property (nonatomic, strong) UITableView *tabView;
@property (nonatomic, strong) NSMutableArray *dataSource;

@end

@implementation GMMyClassVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"我的课件";
    self.view.backgroundColor = kWhiteColor;
    [self addRightBarButtonWithFirstImage:[UIImage imageNamed:@"search-white-64"] action:@selector(searchBtnClick)];
    [self.tabView registerNib:[UINib nibWithNibName:@"GMMyClassCell" bundle:nil] forCellReuseIdentifier:@"GMMyClassCell"];
    [self getMyRes];
}
- (void)getMyRes{
    self.pageIndex = 0;
    NSDictionary *dict= @{@"from":FROM_IOS,
                          @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                          @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                          @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                          @"pageIndex":@(self.pageIndex),
                          @"pageSize":@(10),
                          @"key":self.searchText?self.searchText:@""
                          };
    kWeakObject(self)

    [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetMyRes&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [weakself.tabView.mj_header endRefreshing];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSArray *arr = [GMMyclassModel mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:RESULT_NAME_Data]];
                [self.dataSource removeAllObjects];
                [self.dataSource addObjectsFromArray:arr];
                [weakself.tabView.mj_footer endRefreshing];
                [weakself.tabView.mj_header endRefreshing];
                if (weakself.dataSource.count == 0) {
                    [weakself.tabView setupEmptyDataText:@"暂无数据" secoundText:@"" buttonTit:@"" verticalOffset:0 emptyImage:NODATAIMG tapBlock:^{
                        
                    } butClick:^{
                        
                    }];
                }
                [weakself.tabView reloadData];
            }else{
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:self.view];
        }
    }];
}
- (void)getMoreMyRes{
    self.pageIndex ++;
    NSDictionary *dict= @{@"from":FROM_IOS,
                          @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                          @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                          @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                          @"pageIndex":@(self.pageIndex),
                          @"pageSize":@(10),
                          @"key":self.searchText?self.searchText:@""
                          };
    kWeakObject(self)
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=GetMyRes&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSArray *arr = [GMMyclassModel mj_objectArrayWithKeyValuesArray:[responseObject objectForKey:RESULT_NAME_Data]];
                [self.dataSource addObjectsFromArray:arr];
                if (arr.count>0) {
                    [weakself.tabView.mj_footer endRefreshing];
                    [weakself.tabView.mj_header endRefreshing];
                    [weakself.tabView reloadData];
                }else{
                    weakself.tabView.mj_footer.state = MJRefreshStateNoMoreData;
                }
            }else{
                [weakself.tabView.mj_footer endRefreshing];
                [weakself.tabView.mj_header endRefreshing];
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [weakself.tabView.mj_footer endRefreshing];
            [weakself.tabView.mj_header endRefreshing];
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}
- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource =[[NSMutableArray alloc]init];
    }
    return _dataSource;
}
- (UITableView *)tabView{
    if (!_tabView) {
        _tabView =[UITableView zj_tableViewWithSuperview:self.view delegate:self style:UITableViewStylePlain constraints:^(MASConstraintMaker *make) {
            make.top.leading.trailing.equalTo(self.view);
            if (CYL_IS_IPHONE_X) {
                make.bottom.equalTo(self.view).offset(-34);
            }else{
                make.bottom.equalTo(self.view);
            }
        }];
        [_tabView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        _tabView.showsVerticalScrollIndicator =NO;
        
        _tabView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getMyRes)];
        _tabView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(getMoreMyRes)];
        _tabView.mj_footer.hidden =YES;

    }
    return _tabView;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    self.tabView.mj_footer.hidden = self.dataSource.count > 0? NO:YES;
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    GMMyClassCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GMMyClassCell" forIndexPath:indexPath];
    GMMyclassModel *model = self.dataSource[indexPath.row];
    cell.model = model;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 80.f;
}
-(void)searchBtnClick{
    PYSearchViewController *searchViewController = [PYSearchViewController searchViewControllerWithHotSearches:nil searchBarPlaceholder:@"请输入商品名称进行搜索" didSearchBlock:^(PYSearchViewController *searchViewController, UISearchBar *searchBar, NSString *searchText) {
        self.searchText = searchText;
        [self dismissViewControllerAnimated:YES completion:^{
            [self getMyRes];
        }];
    }];
    searchViewController.searchTextField.textColor = [UIColor colorWithHexString:@"101010" andAlpha:1.0];
    searchViewController.searchTextField.tintColor = [UIColor colorWithHexString:@"101010" andAlpha:1.0];
    searchViewController.searchTextField.font = [UIFont systemFontOfSize:10.0f];
    searchViewController.searchBar.layer.cornerRadius = 16;
    searchViewController.searchBar.clipsToBounds = YES;
    searchViewController.searchBar.layer.borderWidth = 0.5;
    searchViewController.searchBar.layer.borderColor = [UIColor colorWithHexString:@"D7D7D7" andAlpha:1.0].CGColor;
    [searchViewController.cancelButton setTitleColor:kWhiteColor forState:UIControlStateNormal];
    searchViewController.cancelButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    
    searchViewController.delegate = self;
    searchViewController.hotSearchStyle = PYHotSearchStyleDefault;
    searchViewController.searchHistoryStyle = PYSearchHistoryStyleARCBorderTag;
    GMBaseNavigationController *base = [[GMBaseNavigationController alloc]initWithRootViewController:searchViewController];
    [self presentViewController:base animated:YES completion:nil];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
     GMMyclassModel *model = self.dataSource[indexPath.row];
    if (model.NormalCode >0) {
        if (model.NormalCode ==1) {
            [MBProgressHUD showErrorOrSuc:@"关联资源已下架或不可用" toView:self.view];
        }else if (model.NormalCode ==2){
            [MBProgressHUD showErrorOrSuc:@"当前手机型 号非购买资源所用手机型号，你可以到“我的 - 主页 - 个人资料(付费资源管理)”模块申请变更手机型号。" toView:self.view];
        }else if (model.NormalCode ==3){
            [MBProgressHUD showErrorOrSuc:@"本期培训已结束，课件自动关闭；若有需要请报名参加下期培训。" toView:self.view];
        }
    }else{
        if ([model.ResType isEqualToNumber:@(1)]) {
            /**视频*/
            GMPlayerViewController *play = [[GMPlayerViewController alloc] init];
            play.resId = model.Id;
            [self.navigationController pushViewController:play animated:YES];
            
        }else if ([model.ResType isEqualToNumber:@(2)]){
            /**文档*/
            GMReadPDFVC *file = [[GMReadPDFVC alloc] init];
            file.resId = model.Id;
            [self.navigationController pushViewController:file animated:YES];
        }else if ([model.ResType isEqualToNumber:@(3)]){
            /**习题*/
            GMExercisesVC *exercises =[[GMExercisesVC alloc] init];
            exercises.resId = model.Id;
            [self.navigationController pushViewController:exercises animated:YES];
            
        }else if ([model.ResType isEqualToNumber:@(4)]){
            /**试卷*/
            GMExaminationVC *exam = [[GMExaminationVC alloc] init];
            exam.resId = model.Id;
            [self.navigationController pushViewController:exam animated:YES];
            
        }else if ([model.ResType isEqualToNumber:@(9)]){
            /**课程包*/
            GMCoursePackageVC *package = [[GMCoursePackageVC alloc] init];
            package.resId = model.Id;
            package.titleStr = model.Name;
            [self.navigationController pushViewController:package animated:YES];
        }
    }
}

@end
